import doT from '../../../../vendor/template/doT.js';
import { auditStateToHtml } from '../../../common/json-mapping/state-content-mapping.js';
import watermark from '../../../common/watermark.js';
import InboundPlanApi from '../../../common/api/breed/inboundplan.api.js';

(function (window, document, $) {
    const salesplanmainTemplate = doT.template($('#salesplanmain-template').text());
    let openId = Utils.GetSessionStorage('openId');
    let _vm,
        _res,
        resTotal = [],
        listindex = '',
        operatarr = [],
        index,
        subdataWarList = [];
    let _page = {
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    };
    $(async function () {
        _vm = new Vue({
            el: '#salesplanmain',
            data() {
                return {
                    salesplanList: [],
                    page: { ..._page },
                };
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        await getSystemParam();
        _initCommand();
        _search(); // 搜索
        _initSlide(); // 下拉加载
        _ctlReturn(); // 控制返回按钮，返回的页面
        pullLoad(); // 上拉加载
        _returnMain(); // 返回首页
        liststatues();
        _watermarkBgImg(); // 添加水印信息
    });

    //TODO : 命名初始化
    const _initCommand = () => {
        // 新增按钮
        $('#addsaleorders').on('click', function (e) {
            window.sessionStorage.removeItem('perinplanList');
            location.href = `../inboundplan/addothercarplan.html?v=${Utils.GetTime()}`;
        });

        // 显示功能可视区
        $(document).on('click', '.ellipsis', function (e) {
            $(document).off('click', '.looksale');
            e.stopPropagation();
            $('.saleElp').siblings('.detail').css('display', 'none');
            $(this).parents('.salesplanstate').siblings('.detail').css('display', 'block');
            index = $(this).parents('.looksale').index();
            let billindex = resTotal[index].billStatus;
            let $opration = $(this).parents('.saleElp').siblings('.detail');
            // 已保存
            if (billindex === 1) {
                $opration.find('.savesale').css('display', 'none');
                $opration.find('.settle').css('display', 'none');
                $opration.find('.generate').css('display', 'none');
            }
            // 已提交
            if (billindex === 2) {
                $opration.find('.subsale').css('display', 'none');
                $opration.find('.settle').css('display', 'none');
                $opration.find('.generate').css('display', 'none');
            }
            // 已审核
            if (billindex === 3) {
                $opration.find('.antiaudit').siblings().css('display', 'none');
                $opration.find('.viewdetails').css('display', 'block');
                $opration.find('.generate').css('display', 'block');
            }
        });

        // 点击功能可视区之外的区域
        $(document).bind('click', function (e) {
            var target = $(e.target);
            if (target.closest('.saleElp').length == 0) {
                //点击可视区域.saleElp之外的地方触发
                $('.saleElp').siblings('.detail').css('display', 'none');
            }
            // 点击整行跳转详情页面
            // $(document).on('click', '.looksale', function (e) {
            //     $(document).off('click', '.looksale');
            //     index = $(this).index();
            //     location.href = `./inboundplaninfo.html?v=${Utils.GetTime()}&id=${resTotal[index].id}`;
            // });
        });

        // // 点击整行跳转详情页面
        // $(document).on('click', '.looksale', function (e) {
        //     e.stopPropagation();
        //     $(document).off('click', '.looksale');
        //     index = $(this).index();
        //     location.href = `./inboundplaninfo.html?v=${Utils.GetTime()}&id=${resTotal[index].id}`;
        // });

        // 操作
        $(document).on('click', '.saledetail li:not(.operation)', function (e) {
            e.stopPropagation();
            index = $(this).parents('.looksale').index();
            let operat = $(this).index();
            operatsales(resTotal[index].id, operat);
            $(this).parents('.detail').css('display', 'none');
        });

        // 查看详情
        // $(document).on('click', '.viewdetails', function (e) {
        //     e.stopPropagation();
        //     index = $(this).parents('.looksale').index();
        //     $(this).parents('.detail').css('display', 'none');
        //     location.href = `./inboundplaninfo.html?v=${Utils.GetTime()}&id=${resTotal[index].id}`;
        // });

        // 编辑
        $(document).on('click', '#editInfo', function (e) {
            e.stopPropagation();
            let id = $(this).data('id');
            location.href = `./addothercarplan.html?v=${Utils.GetTime()}&id=${id}`;
        });

        // 提交
        $(document).on('click', '#submitInfo', function (e) {
            e.stopPropagation();
            let id = $(this).data('id');
            index = $(this).data('index');
            let billNo = $(this).data('no');
            operatsales(id, '提交', billNo);
        });

        // 删除
        $(document).on('click', '#deleteInfo', function (e) {
            console.log(resTotal);
            e.stopPropagation();
            let id = $(this).data('id');
            index = $(this).data('index');
            let billNo = $(this).data('no');
            operatsales(id, '删除', billNo);
        });

        // 审核
        $(document).on('click', '#auditInfo', function (e) {
            console.log(resTotal);
            e.stopPropagation();
            let id = $(this).data('id');
            index = $(this).data('index');
            let billNo = $(this).data('no');
            operatsales(id, '审核', billNo);
        });

        // 签到
        $(document).on('click', '#signInfo', function (e) {
            console.log(resTotal);
            e.stopPropagation();
            let id = $(this).data('id');
            index = $(this).data('index');
            let destFarmName = resTotal[index]?.destFarm?.name;
            window.sessionStorage.removeItem('destFarmName');
            Utils.SetSessionStorage('destFarmName', destFarmName);
            location.href = `./inboundplansign.html?v=${Utils.GetTime()}&id=${id}`;
        });

        // 签到
        // $(document).on('click', '#sign', function (e) {
        //     console.log(resTotal)
        //     e.stopPropagation()
        //     let id = 'gd0caOcpLzRZ';
        //     let destFarmName = '那隆猪厂';
        //     window.sessionStorage.removeItem("destFarmName");
        //     Utils.SetSessionStorage("destFarmName", destFarmName);
        //     location.href = `./inboundplansign.html?v=${Utils.GetTime()}&id=${id}`;
        // })
    };

    // 提示
    const operatsales = (id, operat, billNo) => {
        console.log(index);

        console.log(resTotal[index]);
        $.modal({
            autoClose: false,
            title: `${operat}提示`,
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div  style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认${operat}<span style="color:red">[${billNo}]</span > 单据？该操作无法撤销！</div >
					</div > `,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '确定',
                    onClick: function () {
                        _initPage();
                        switch (operat) {
                            case '删除':
                                InboundPlanApi.delEntryplans(id, {
                                    openId: openId,
                                }).then((res) => {
                                    _initDataTable();
                                    $.toptip('删除成功。', 'success');
                                    $.closeModal();
                                });
                                break;
                            case '提交':
                                InboundPlanApi.submitInboundPlan([id]).then((res) => {
                                    _initDataTable();
                                    $.toptip('提交成功。', 'success');
                                    $.closeModal();
                                });
                                break;
                            case '反提交':
                                InboundPlanApi.rollSubmitInboundPlan([id])
                                    .then((res) => {
                                        _initDataTable();
                                        $.toptip('反提交成功。', 'success');
                                        $.closeModal();
                                    })
                                    .catch(() => {
                                        _initDataTable();
                                        $.closeModal();
                                    });
                                break;
                            case '审核':
                                InboundPlanApi.auditInboundPlan([id])
                                    .then((res) => {
                                        _initDataTable();
                                        $.toptip('审核成功。', 'success');
                                        $.closeModal();
                                    })
                                    .catch(() => {
                                        _initDataTable();
                                        $.closeModal();
                                    });
                                break;
                            case '反审核':
                                InboundPlanApi.rollAuditInboundPlan([id])
                                    .then((res) => {
                                        _initDataTable();
                                        $.toptip('反审核成功。', 'success');
                                        $.closeModal();
                                    })
                                    .catch(() => {
                                        _initDataTable();
                                        $.closeModal();
                                    });
                                break;
                        }
                    },
                },
            ],
        });
    };

    // 请求列表数据 66
    const _initDataTable = async () => {
        // 查询销售出库单H5列表
        let _data = _vm.page;
        InboundPlanApi.othercarplanlist(
            Object.assign(
                {
                    billNo: $('#search-index').val(),
                    billStatus: listindex,
                    sort: 'bizFormObj.createTime desc',
                },
                _data,
            ),
        ).then((res) => {
            _page = {
                pageSize: 10,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            };
            _vm._data.page = Object.assign({}, _page);
            res.items.forEach((item) => {
                item.isolationPoint = subdataWarList.find((s) => s.farm.includes(item.destFarm?.name))?.name || '';
            });
            _res = res.items;
            resTotal.push(..._res);
            _res.forEach((ele) => {
                let confirm = [];
                ele.billStatusCh = auditStateToHtml(ele.bizFormObj.billStatus);
                ele.confirmNum = confirm.length;
            });
            _vm.salesplanList = [];
            _vm.salesplanList = [..._vm.salesplanList, ...resTotal];
            $('.looksale:last').css('margin-bottom', '10px');
            $('#salesplantel').empty().append(salesplanmainTemplate(_vm.salesplanList));
            $('.looksale')
                .eq(0)
                .find('.saledetail')
                .each(function (index, domele) {
                    operatarr = $(domele).text().trim().split(' ');
                });
            $('.looksale:last').css('margin-bottom', '120px');
        });
    };

    // 导航栏
    const liststatues = () => {
        $('#spleplan-navbar a').on('click', function () {
            listindex = Number($(this).index());
            $(this).addClass('weui-bar__item--on').siblings().removeClass('weui-bar__item--on');
            if (listindex === 0) {
                listindex = '';
            }
            _initPage();
            _initDataTable();
        });
    };

    // 搜索
    const _search = () => {
        // 表单提交
        $('#search_bar form').submit(function () {
            _initPage();
            _initDataTable();
            return false;
        });
        // 搜索框为空
        if (!Utils.IsNotNull($('#search-index').val())) {
            _initPage();
            _initDataTable();
        }
        // 取消搜索
        $('#search_cancel').on('click', function () {
            $('#search-index').val('');
            _initPage();
            _initDataTable();
        });
        // *
        $('#search_clear').on('click', function () {
            $('#search-index').val('');
            _initPage();
            _initDataTable();
        });
    };

    // 初始化分页
    const _initPage = () => {
        resTotal = [];
        _page = {
            pageSize: 10,
            pageIndex: 0,
            totalPages: -1,
        };
        _vm._data.page = Object.assign({}, _page);
    };

    // 下拉加载
    const _initSlide = () => {
        //分别设置滑动距离，开始位置，结束位置，和模拟数据的定时器
        let disY, startY, endY, timer, t, pullheight;
        // 触摸开始
        $('#salesplantel').on('touchstart', function (e) {
            startY = e.originalEvent.changedTouches[0].pageY; //开始时的坐标
        });
        // 移动中
        $('#salesplantel').on('touchmove', function (e) {
            $('.saleElp').siblings('.detail').css('display', 'none');
            //点击整行跳转详情页面
            // $(document).on('click', '.looksale', function (e) {
            //     $(document).off('click', '.looksale');
            //     index = $(this).index();
            //     location.href = `./entryrgstinfo.html ? v = ${Utils.GetTime()}& id=${resTotal[index].id} `;
            // });
            endY = e.originalEvent.changedTouches[0].pageY;
            disY = endY - startY; //移动后的坐标减去开始坐标，滑动距离。
            if (isTop() && disY > 0) {
                e.preventDefault();
            }
            if (disY < 60) {
                $('#pull-down').css({
                    height: disY + 'px', //父盒子的高度随着滑动距离变化，有最大值。
                });
            } else {
                $('#pull-down').css({
                    height: 60 + 'px', //父盒子的最大高度
                });
            }
            // 结束时
            $('#salesplantel').on('touchend', function (e) {
                clearInterval(timer);
                endY = e.originalEvent.changedTouches[0].pageY;
                disY = endY - startY;
                if (isTop() && disY > 0) {
                    timer = setInterval(function () {
                        $('#pull-down').css({
                            height: 0 + 'px', //松手后的返回。
                        });
                        clearInterval(timer);
                        _initPage();
                        _initDataTable(); //加载数据
                    }, 300);
                } else {
                    $('#pull-down').css({
                        height: 0 + 'px', //松手后的返回。
                    });
                }
                $('#salesplantel').off('touchend');
            });
        });
    };
    const isTop = () => {
        var t = document.documentElement.scrollTop || document.body.scrollTop;
        return t === 0 ? true : false;
    };

    //TODO : 上拉加载
    const pullLoad = () => {
        // 监听滚动的父容器
        $('body')
            .infinite()
            .on('infinite', function () {
                let _data = _vm._data.page;
                if (_data.pageIndex == _data.totalPages) return;
                let self = this;
                if (self.loading) return;
                self.loading = true;
                setTimeout(function () {
                    _initDataTable();
                    self.loading = false;
                }, 500); //模拟延迟
            });
    };

    // 控制返回按钮，返回的页面
    const _ctlReturn = () => {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function () {
                history.pushState(null, null, document.URL);
                //跳转列表
                this.window.location = `../../main.html`;
            });
        }
    };

    //返回首页
    const _returnMain = () => {
        $('#returnMain').on('click', function () {
            location.href = '../../main.html';
        });
    };

    // 添加水印信息
    const _watermarkBgImg = () => {
        let _userInfo = JSON.parse(Utils.GetSessionStorage('SNAccountEply')) || {};
        watermark.set(_userInfo.name + _userInfo.numCode); // 水印
    };

    const getSystemParam = async () => {
        // 获取系统参数：牧场组织
        await InboundPlanApi.getPrmtSettings('LIVESTOCK-ISOLATION').then((result) => {
            subdataWarList = JSON.parse(result);
        });
    };
})(window, document, jQuery);
